/**
 * @param {number[][]} triangle
 * @return {number}
 */
var minimumTotal = function (triangle) {
  let m = triangle.length
  let n = triangle[0].length
  let dp = new Array(m).fill(0).map(() => new Array(n).fill(0))
  dp[0][0] = triangle[0][0]
  for (let i = 1; i < m; i++) {
    dp[i][0] = dp[i - 1][0] + triangle[i][0]
  }
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < triangle[i].length; j++) {
      if (dp[i - 1][j]!=undefined) {

        dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j]
      } else {
        dp[i][j] = dp[i - 1][j - 1] + triangle[i][j]
      }
    }
  }
  // console.log(dp);
  return Math.min(...dp[m - 1])
}

console.log(
  minimumTotal([
    [7],
    [-5, 9], //  2 16
    [6, 5, 2], //     8  7  18
    [-8, -2, -7, 3], //0 -5  0   21
    [-2, 6, -6, -1, 4],
  ]) //-2
)

/**
 *
 *       7
 *     -5 9
 *     6 5 2
 *  -8 -2 -7 3
 * -2 6 -6 -1 4
 */
